package com.wlf.admin.common.config;

import com.wlf.admin.common.dto.CacheKey;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.ehcache.event.EventType;
import org.ehcache.impl.config.event.DefaultCacheEventListenerConfiguration;
import org.ehcache.jsr107.Eh107Configuration;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.stream.Collectors;

@Configuration //配置类
public class CacheConfig {
    /**
     * 缓存操作打印
     */
    @Slf4j
    public static class EventLogger implements CacheEventListener<Object, Object> {
        @Override
        public void onEvent(CacheEvent<?, ?> event) {
            log.debug("Event: " + event.getType() + " Key: " + event.getKey() + " old value: " + event.getOldValue() + " new value: " + event.getNewValue());
        }
    }

    @Bean
    public JCacheManagerCustomizer jCacheManagerCustomizer() {

        CacheConfiguration<Long, Object> baseCacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, Object.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
                                .heap(100, EntryUnit.ENTRIES)  // 堆缓存大小为 100 个条目
                                .offheap(10, MemoryUnit.MB) // 堆外缓存大小为 10 MB
                        // .disk(30, MemoryUnit.MB, true)
                )
                .withService(new DefaultCacheEventListenerConfiguration(Arrays.stream(EventType.values()).collect(Collectors.toSet()), new EventLogger()))
                // 设置缓存的空闲时间为 60 秒
                .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(60)))
                .build();
        return cm -> {
            for (String cacheName : new HashSet<>(CacheKey.cacheNames)) {
                cm.createCache(cacheName, Eh107Configuration.fromEhcacheCacheConfiguration(baseCacheConfig));
            }
        };
    }
}
